package com.example.administrator.jim.view.main;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bumptech.glide.Glide;
import com.example.administrator.jim.BaseActivity;
import com.example.administrator.jim.MainActivity;
import com.example.administrator.jim.R;
import com.example.administrator.jim.adapter.Mine_ViewSetting_ListViewAdapter;
import com.example.administrator.jim.bean.JsonBean;
import com.example.administrator.jim.bottomdialog.CameraSettingBottomDialog;
import com.example.administrator.jim.bottomdialog.GenderSettingBottomDialog;
import com.example.administrator.jim.bottomdialog.NiknameSettingBottomDialog;
import com.example.administrator.jim.bottomdialog.SignatureSettingBottomDialog;
import com.example.administrator.jim.utils.CameraUtils;
import com.example.administrator.jim.utils.GetJsonDataUtil;
import com.google.gson.jpush.Gson;
import com.sdsmdg.tastytoast.TastyToast;

import org.json.JSONArray;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import agency.tango.android.avatarview.IImageLoader;
import agency.tango.android.avatarview.loader.PicassoLoader;
import agency.tango.android.avatarview.views.AvatarView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.event.MyInfoUpdatedEvent;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

/**
 * Created by BarBrothers on 2017/12/17.
 */

public class Mine_SettingActivity extends BaseActivity {
    private CameraUtils mCameraUtils;
    private File mUsericon;
    //解析城市数据线程
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private Thread thread;
    //加载头像工具
    IImageLoader imageLoader;
    private String desc[]=new String[5];
    private TimePickerView mTimePickerView_birthdry;
    private int icons[]={R.mipmap.mine_setting_nikename,R.mipmap.mine_setting_xingbie,R.mipmap.mine_setting_shengri,R.mipmap.mine_setting_weizhi,R.mipmap.mine_setting_bianji};
    private String titles[]={"昵称","性别","生日","地区","个性签名"};
    @BindView(R.id.minesetting_view_avaimageview)
    AvatarView mAvatarView_usericon;
    @BindView(R.id.minesetting_view_username)
    TextView mtextview_username;
    @BindView(R.id.minesetting_listview)
    ListView mListView;
    @BindView(R.id.minesetting_view_signature)
    TextView mTextView_signature;
    @BindView(R.id.minesetting_imageview_camera)
    ImageView mImageView_camera;
    private Handler mhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    MainActivity.mMyInfo = JMessageClient.getMyInfo();
                    initUsericon();
                    initUserinfo();
                    mMine_viewSetting_listViewAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    private Mine_ViewSetting_ListViewAdapter mMine_viewSetting_listViewAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_minesetting);
        setClazz(Mine_SettingActivity.class);
        getSupportActionBar().hide();
        ButterKnife.bind(this);
        initDatas();    }
    public void updateUserInfo(){
        MainActivity.updateflag=true;
        //更新用户数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    mhandler.sendEmptyMessage(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void onEventMainThread(MyInfoUpdatedEvent event){
        //当服务器数据更新时对显示的数据进行更新
        MainActivity.mMyInfo = event.getMyInfo();
        initUsericon();
        initUserinfo();
        mMine_viewSetting_listViewAdapter.notifyDataSetChanged();
    }
    @Override
    protected void onResume() {
        super.onResume();
//        更新用户数据
        MainActivity.mMyInfo = JMessageClient.getMyInfo();
        initUsericon();
        initUserinfo();
        mMine_viewSetting_listViewAdapter.notifyDataSetChanged();
    }
    private void initDatas() {
        mCameraUtils=new CameraUtils(this);
        //解析城市数据
        initCityDatas();
        initUsericon();
        initUserinfo();
        initListDatas();
        initListener();
        initTimePicker();
    }

    private void initCityDatas() {
        if (thread==null){//如果已创建就不再重新创建子线程了
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 写子线程中的操作,解析省市区数据
                    initJsonData();
                }
            });
            thread.start();
        }
    }
    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this,"province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i=0;i<jsonBean.size();i++){//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c=0; c<jsonBean.get(i).getCityList().size(); c++){//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        ||jsonBean.get(i).getCityList().get(c).getArea().size()==0) {
                    City_AreaList.add("");
                }else {

                    for (int d=0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }
    //显示城市选择器
    private void ShowCityPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText()+"-"+
                        options2Items.get(options1).get(options2)+"-"+
                        options3Items.get(options1).get(options2).get(options3);
                MainActivity.mMyInfo.setAddress(tx);
                JMessageClient.updateMyInfo(UserInfo.Field.address, MainActivity.mMyInfo, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        if(i==0){
                            TastyToast.makeText(getApplicationContext(), "修改成功!", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                            updateUserInfo();
                        }else {
                            TastyToast.makeText(getApplicationContext(), "修改失败!", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                        }
                    }
                });

            }
        })
                .setTitleText("城市选择")
                .setDividerColor(Color.DKGRAY)
                .setSubmitColor(Color.DKGRAY)
                .setCancelColor(Color.DKGRAY)
                .setTextColorCenter(Color.DKGRAY) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器
        pvOptions.show();
    }
    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
    private void initListDatas(){
        mMine_viewSetting_listViewAdapter = new Mine_ViewSetting_ListViewAdapter(this,icons,titles,desc);
        mListView.setAdapter(mMine_viewSetting_listViewAdapter);
    }
    //加载时间选择器
    private void initTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        //时间选择器
        mTimePickerView_birthdry = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                MainActivity.mMyInfo.setBirthday(getTime(date));
                JMessageClient.updateMyInfo(UserInfo.Field.birthday, MainActivity.mMyInfo, new BasicCallback() {
                    @Override
                    public void gotResult(int i, String s) {
                        if(i==0){
                            TastyToast.makeText(getApplicationContext(), "修改成功!", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                            updateUserInfo();
                        }else {
                            TastyToast.makeText(getApplicationContext(), "修改失败!", TastyToast.LENGTH_SHORT, TastyToast.SUCCESS);
                        }
                    }
                });
                updateUserInfo();
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                //默认选择当前日期
                .setDate(Calendar.getInstance())
                .setSubmitColor(Color.DKGRAY)
                .setCancelColor(Color.DKGRAY)
//                .setBackgroundId(0x00FFFFFF) //设置外部遮罩颜色
                .setDecorView(null)
                .build();
    }
    //转换时间为long类型提交
    private long getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        long time=0;
        try {
            time = format.parse(format.format(date)).getTime();
        }catch (Exception e){}

        return time;
    }
    //转换时间为年月日显示
    private String paseTime(long time) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date= new Date(time);
        return format.format(date);
    }
    private void initListener(){
       mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
               switch (i){
                   case 0:
                       NiknameSettingBottomDialog niknamedialog = new NiknameSettingBottomDialog();
                       niknamedialog.show(getSupportFragmentManager());
                       break;
                   case 1:
                       GenderSettingBottomDialog genderdialog = new GenderSettingBottomDialog();
                       genderdialog.show(getSupportFragmentManager());
                       break;
                   case 2:
                       mTimePickerView_birthdry.show();
                       break;
                   case 3:
                       ShowCityPickerView();
                       break;
                   case 4:
                       SignatureSettingBottomDialog signaturedialog = new SignatureSettingBottomDialog();
                       signaturedialog.show(getSupportFragmentManager());
                       break;
               }
           }
       });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCameraUtils.initImage(requestCode,data,mAvatarView_usericon);
    }

    private void initUserinfo(){
        if(MainActivity.mMyInfo!=null){
            //列表数据
            desc[0]=MainActivity.mMyInfo.getNickname();
            if(String.valueOf(MainActivity.mMyInfo.getGender()).equals("male")) {
                desc[1]="男";
            }else if(String.valueOf(MainActivity.mMyInfo.getGender()).equals("female")) {
                desc[1]="女";
            }else {
                desc[1]="保密";
            }
            if(String.valueOf(MainActivity.mMyInfo.getBirthday()).equals("0")||MainActivity.mMyInfo.getBirthday()<0){
                desc[2]="";
            }else {
                desc[2]=paseTime(MainActivity.mMyInfo.getBirthday());
            }
            desc[3]=MainActivity.mMyInfo.getAddress();
            desc[4]=MainActivity.mMyInfo.getSignature();
            //个性签名
            mTextView_signature.setText(MainActivity.mMyInfo.getSignature());
        }
    }
    private void initUsericon() {
        if(MainActivity.mMyInfo!=null){
            mUsericon = MainActivity.mMyInfo.getBigAvatarFile();
            imageLoader = new PicassoLoader();
            if(mUsericon!=null){
                Glide.with(this).load(mUsericon).into(mAvatarView_usericon);
            }else {
                Glide.with(this).load(R.mipmap.aurora_headicon_default).into(mAvatarView_usericon);
            }
                mtextview_username.setText(MainActivity.mMyInfo.getUserName());
        }
    }
    @OnClick({R.id.minesetting_title_mine_huitui,R.id.minesetting_imageview_camera})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.minesetting_title_mine_huitui:
                finish();
                break;
            case R.id.minesetting_imageview_camera:
                CameraSettingBottomDialog cameraSettingBottomDialog = new CameraSettingBottomDialog();
                cameraSettingBottomDialog.setCameraUtils(mCameraUtils);
                cameraSettingBottomDialog.show(getSupportFragmentManager());
                break;
        }
    }
}
